package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取用户信息并保存到ThreadLocal中
 *
 * @Author wd
 * @Date 2025/6/20 15:02
 */

public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求头中的userId
        String userInfo = request.getHeader("user-info");
        if(StrUtil.isNotBlank(userInfo)) {
            Long userId = Long.valueOf(userInfo);
            UserContext.setUser(userId);
        }
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();//释放用完的用户ID，避免内存泄漏
    }
}
